package com.collect.cameroon.zhiScene.v2.zhiPerfermanceV2;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.collect.cameroon.R;
import com.collect.cameroon.zhiAdater.zhiPerfermance.CTPerfermanceAdjuster;
import com.collect.cameroon.zhiBase.BaseActivity;
import com.collect.cameroon.zhiBean.zhiReceive.ZHIRPerfermanceEntity;
import com.collect.cameroon.zhiBean.zhiReceive.ZHIRPerfermanceListEntity;
import com.collect.cameroon.zhiBean.zhiSend.ZHISPerfermanceEntity;
import com.collect.cameroon.zhiGlobal.zhiAppSettings.ZHIProjectRouter;
import com.collect.cameroon.zhiGlobal.zhiEnumMainType.ZHIQueryLevel;
import com.collect.cameroon.zhiHelper.ZHIPerfermanceHelper;
import com.collect.cameroon.zhiScene.zhiWidget.zhiNavigationBar.ZHINavigationBar;
import com.collect.cameroon.zhiUtils.StringUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@SuppressLint("NonConstantResourceId")
@Route(path = ZHIProjectRouter.ZHI_Perfermance)
public class ZHIPerfermanceActivityV2 extends BaseActivity<ZHIPerfermancePresenter> implements ZHIPerfermanceContract.View {

    @BindView(R.id.navigationBar)
    ZHINavigationBar navigationBar;

    @BindView(R.id.srl_swipe_layout)
    SwipeRefreshLayout srl_swipe_layout;

    @BindView(R.id.tv_perfermance_month)
    TextView tv_perfermance_month;

    @BindView(R.id.tv_perfermance_level)
    TextView tv_perfermance_level;

    @BindView(R.id.tv_perfermance_collect_repay_rate)
    TextView tv_perfermance_collect_repay_rate;

    @BindView(R.id.rc_list)
    RecyclerView rc_list;
    @BindView(R.id.tv_query_count)
    TextView tv_query_count;

    CTPerfermanceAdjuster mCTPerfermanceAdjuster = new CTPerfermanceAdjuster();

    private OptionsPickerView mOptionsPickerView;
    private List<String> mOptionList;
    private List<String> mMonthList;
    boolean isMonthPick = false;

    private final Calendar mCalendar = Calendar.getInstance();
    private int mMonth = 0;
    private String mLevel = "ALL";

    @Override
    protected void initInjector() {
        mActivityComponent.inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_perfermance_v2;
    }

    @Override
    protected void initView() {
        try {
            srl_swipe_layout.setColorSchemeColors(getResources().getColor(R.color.theme_color_0));
            //TimePickerView mTimePickerView = showDatePicker(getActivity());

            navigationBar.showLeft().hideRight().setCenterText(getString(R.string.page_perfermance)).setBarClickListener(new ZHINavigationBar.OnNavigationBarClickListener() {
                @Override
                public void onNavigationBarLeftClick(View v) {
                    finish();
                }

                @Override
                public void onNavigationBarRightClick(View v) {
                }
            });

            mMonth = (mCalendar.get(Calendar.MONTH) + 1);

            mOptionList = new ArrayList<String>();
            mOptionList.add(ZHIQueryLevel.QUERY_LEVEL_ALL);
            mOptionList.add(ZHIQueryLevel.QUERY_LEVEL_B1);
            mOptionList.add(ZHIQueryLevel.QUERY_LEVEL_B2);
            mOptionList.add(ZHIQueryLevel.QUERY_LEVEL_B3);
            mOptionList.add(ZHIQueryLevel.QUERY_LEVEL_B4);
            mOptionList.add(ZHIQueryLevel.QUERY_LEVEL_B5);

            mMonthList = new ArrayList<String>();
            for (int i = 1; i < 13; i++) {
                mMonthList.add(i + "");
            }
            initOptionsPickerView();

            initEvent();
            initData(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @OnClick({R.id.ll_perfermance_month, R.id.ll_perfermance_level})
    public void onClick(@NonNull View v) {
        if (v.getId() == R.id.ll_perfermance_month) {
//            mTimePickerView.show();
            isMonthPick = true;
            mOptionsPickerView.setPicker(mMonthList);
            mOptionsPickerView.show();
        } else if (v.getId() == R.id.ll_perfermance_level) {
            isMonthPick = false;
            mOptionsPickerView.setPicker(mOptionList);
            mOptionsPickerView.show();
        }
    }

    @Override
    public void onGetErrorInfo() {
        srl_swipe_layout.setRefreshing(false);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onGetLatestPerfermanceListV2(ZHIRPerfermanceListEntity perfermanceListEntity, ZHISPerfermanceEntity zhisPerfermanceEntity) {
        srl_swipe_layout.setRefreshing(false);
        try {
            //10月15号之前的不显示
            ArrayList<ZHIRPerfermanceEntity> formatPerfermanceEntities = new ArrayList<>();
            ArrayList<ZHIRPerfermanceEntity> perfermanceEntities = perfermanceListEntity.getDataList();
            for (int i = 0; i < perfermanceEntities.size(); i++) {
                ZHIRPerfermanceEntity zhiRPerfermanceEntity = perfermanceEntities.get(i);
                String overdueDate = StringUtil.safeString(zhiRPerfermanceEntity.getOverdueDate());
                if (!isDateBefore1015(overdueDate)) {
                    formatPerfermanceEntities.add(zhiRPerfermanceEntity);
                }
            }

            int gmonth = Integer.parseInt(zhisPerfermanceEntity.getMonth());
            tv_query_count.setText("Total:" + formatPerfermanceEntities.size());
            tv_perfermance_collect_repay_rate.setText((gmonth == 10) ? getResources().getString(R.string.perfermance_calculating) : perfermanceListEntity.getRepayRate());

            mCTPerfermanceAdjuster.setNewData(formatPerfermanceEntities);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint({"InflateParams", "SetTextI18n"})
    public void initEvent() {
        srl_swipe_layout.setOnRefreshListener(() -> initData(false));
//        tv_perfermance_month.setText(mYear + "-" + mMonth + "");
        tv_perfermance_month.setText(mMonth + "");
        tv_perfermance_level.setText(mLevel);

        //设置空布局
        View emptyView = getLayoutInflater().inflate(R.layout.view_empty_no_data, null);
        emptyView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        emptyView.setOnClickListener(v -> initData(true));

        mCTPerfermanceAdjuster.setEmptyView(emptyView);

        rc_list.setLayoutManager(new GridLayoutManager(this.getActivity(), 1));
        rc_list.setAdapter(mCTPerfermanceAdjuster);

        mCTPerfermanceAdjuster.setOnPerfermanceItemClickListener(perfermanceEntity -> {
            ZHIPerfermanceHelper.getInstance().setPerfermanceEntity(perfermanceEntity);
            ZHIProjectRouter.toPerfermanceDetailV2();
        });
    }

    public void initData(boolean showDialog) {
        ZHISPerfermanceEntity zhisPerfermanceEntity = getCaseSearchParams();
        assert mPresenter != null;
        mPresenter.getLatestPerfermanceListV2(getActivity(), zhisPerfermanceEntity, showDialog);
    }

    @SuppressLint({"SimpleDateFormat", "SetTextI18n"})
    private TimePickerView showDatePicker(Context context) {
        OnTimeSelectListener mOnTimeSelectListener = (date, v) -> {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            format.format(date);
            mCalendar.setTime(date);
            mMonth = (mCalendar.get(Calendar.MONTH) + 1);
            tv_perfermance_month.setText(mMonth + "");

            ZHISPerfermanceEntity zhisPerfermanceEntity = getCaseSearchParams();
            assert mPresenter != null;
            mPresenter.getLatestPerfermanceListV2(getActivity(), zhisPerfermanceEntity, true);
        };

        Calendar startCalendar = Calendar.getInstance();
        startCalendar.set(2021, 2, 14);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.set(2030, 9, 15);
        TimePickerView pvTime = new TimePickerBuilder(context, mOnTimeSelectListener)
                .setType(new boolean[]{false, true, false, false, false, false})
                .setCancelText(" ")
                .setContentTextSize(18)
                .setTitleSize(20)
                .setTitleText("")
                .setTitleBgColor(context.getResources().getColor(R.color.theme_blue_4))
                .setTextColorCenter(context.getResources().getColor(R.color.theme_black_0))
                .setOutSideCancelable(true)
                .setRangDate(startCalendar, endCalendar)
                .setTitleColor(context.getResources().getColor(R.color.theme_black_0))
                .setCancelColor(context.getResources().getColor(R.color.white))
                .setSubmitColor(context.getResources().getColor(R.color.white))
                .isDialog(true)
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);
                dialogWindow.setGravity(Gravity.BOTTOM);
                dialogWindow.setDimAmount(0.3f);
            }
        }

        return pvTime;
    }

    private void initOptionsPickerView() {
        OnOptionsSelectListener mOnOptionsSelectListener = (options1, options2, options3, v) -> {
            try {
                if (isMonthPick) {
                    String content = StringUtil.safeString(mMonthList.get(options1));
                    mMonth = Integer.parseInt(content);
                    tv_perfermance_month.setText(content);

                    ZHISPerfermanceEntity zhisPerfermanceEntity = getCaseSearchParams();
                    assert mPresenter != null;
                    mPresenter.getLatestPerfermanceListV2(getActivity(), zhisPerfermanceEntity, true);
                } else {
                    String content = StringUtil.safeString(mOptionList.get(options1));
                    mLevel = StringUtil.safeString(content);
                    tv_perfermance_level.setText(content);

                    ZHISPerfermanceEntity zhisPerfermanceEntity = getCaseSearchParams();
                    assert mPresenter != null;
                    mPresenter.getLatestPerfermanceListV2(getActivity(), zhisPerfermanceEntity, true);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        mOptionsPickerView = new OptionsPickerBuilder(getActivity(), mOnOptionsSelectListener)
                .setTitleText("")
                .setContentTextSize(20)
                .setDividerColor(Color.LTGRAY)
                .setSelectOptions(0)
                .setBgColor(Color.WHITE)
                .setTitleBgColor(getResources().getColor(R.color.theme_color_0))
                .setTitleColor(getResources().getColor(R.color.theme_black_0))
                .setCancelText(" ")
                .setCancelColor(getResources().getColor(R.color.white))
                .setSubmitColor(getResources().getColor(R.color.white))
                .setTextColorCenter(getResources().getColor(R.color.theme_color_0))
                .setOutSideCancelable(true)
                .isRestoreItem(true)
                .isCenterLabel(false)
                .setOutSideColor(0x40000000)
                .setOptionsSelectChangeListener((options1, options2, options3) -> {
                    //String str = "options1: " + options1 + "\noptions2: " + options2 + "\noptions3: " + options3;
                })
                .build();
    }

    private ZHISPerfermanceEntity getCaseSearchParams() {
        ZHISPerfermanceEntity zhisPerfermanceEntity = new ZHISPerfermanceEntity();
        zhisPerfermanceEntity.setMonth(mMonth + "");
        String level = mLevel.contains("ALL") ? "" : mLevel;
        level = level.replace("B", "M");
        zhisPerfermanceEntity.setLeven(level);
        return zhisPerfermanceEntity;
    }

    @SuppressLint("SimpleDateFormat")
    private boolean isDateBefore1015(String overdueDate) {
        try {
            if (TextUtils.isEmpty(overdueDate)) {
                return false;
            }

            overdueDate += " 00:00:00";
            String compareDate = "2020-10-15 00:00:00";

            SimpleDateFormat gformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date gDate = gformat.parse(overdueDate);
            Date gCompareDate = gformat.parse(compareDate);
            return (gDate.getTime() < gCompareDate.getTime());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}